package com.qf.com.qf.like.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qf.com.qf.like.mapper.GrassLikeMapper;
import com.qf.com.qf.like.service.GrassLikeService;
import com.qf.common.core.entity.Grass;
import com.qf.common.core.entity.GrassLike;
import com.qf.common.core.utils.DateUtils;
import com.qf.common.core.utils.UserUtils;
import com.qf.common.redis.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;

/**
 * @author zdl
 * @date 2025/3/28
 */
@Service
public class GrassLikeServiceImpl implements GrassLikeService {
    @Resource
    private GrassLikeMapper grassLikeMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public void like(Integer grassId) {
        Integer uid = UserUtils.getUser();
        // hash存点赞记录
        String likeKey = String.format("like:%s", grassId);
        // 当天点赞数
        String numKey = String.format("likeNum:%s", DateUtils.date2Str(LocalDate.now(), "yyyyMMdd"));
        Integer likeValue = (Integer) redisUtil.hashGet(likeKey, String.valueOf(uid));
        if (likeValue == null || likeValue == 0) {
            // 点赞
            redisUtil.hashPut(likeKey, String.valueOf(uid), 1);
            // 点赞数+1
            redisUtil.hashIncr(numKey, String.valueOf(uid), 1);
            GrassLike grassLike = new GrassLike();
            grassLike.setUid(uid);
            grassLike.setGrassId(grassId);
            grassLikeMapper.insert(grassLike);
        } else {
            // 取消点赞
            redisUtil.hashPut(likeKey, String.valueOf(uid), 0);
            // 点赞数-1
            redisUtil.hashIncr(numKey, String.valueOf(uid), -1);
            // 删除点赞记录
            grassLikeMapper.delete(new LambdaQueryWrapper<GrassLike>()
                    .eq(GrassLike::getUid, uid)
                    .eq(GrassLike::getGrassId, grassId));
        }

    }
}
